package com.yanqu.road.dao.impl.servercenter;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.servercenter.ServerGroup2;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServerGroup2DaoImpl extends TempDao {

    public Map<Integer, Map<Integer, ServerGroup2>> getAllServerGroup2Map() {
        Map<Integer, Map<Integer, ServerGroup2>> groupMap = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_s_server_group2 where openStatus = 1";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                ServerGroup2 data = initServerGroup2(rs);
                if (!groupMap.containsKey(data.getGroupType())) {
                    groupMap.put(data.getGroupType(), new ConcurrentHashMap<>());
                }
                groupMap.get(data.getGroupType()).put(data.getGroupId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return groupMap;
    }

    public Map<Integer, ServerGroup2> getServerGroup2Map(int groupType) {
        Map<Integer, ServerGroup2> groupMap = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_s_server_group2 where openStatus = 1 and groupType = ?";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, groupType);
            rs = call.executeQuery();
            while (rs.next()) {
                ServerGroup2 data = initServerGroup2(rs);
                groupMap.put(data.getGroupId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return groupMap;
    }


    private ServerGroup2 initServerGroup2(ResultSet rs) throws SQLException {
        ServerGroup2 data = new ServerGroup2();
        data.setGroupType(rs.getInt("groupType"));
        data.setGroupId(rs.getInt("groupId"));
        data.setChannelId(rs.getInt("channelId"));
        String serverList = rs.getString("serverList");
        if (!StringUtils.isNullOrEmpty(serverList)) {
            data.setServerList(StringUtils.stringToLongList(serverList, ","));
        }
        return data;
    }
}
